// src/utils/request.ts

import router from "@/router";
import store from "@/stores";
import axios, { type AxiosRequestConfig } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL, // 基础路径
});

// 请求拦截器

//  参考 https://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html
request.interceptors.request.use(
  (config) => {
    config.url = config.url?.trim();
    // const token = store.getters.token
    const token = "";
    if (token) {
      config.headers.Authorization = `Bearer ${token}`; // 注意 Bearer 和 token 之间有一个空格！
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
let _choose = false;
// 响应拦截器
request.interceptors.response.use(
  (response) => {
    //suc
    const status = response.data?.status;
    if (!status || status === 200) {
      return response;
    }
    // //统一处理响应错误，例如 token 无效、服务端异常等
    // ElMessage({ type: "error", message: response.data.message, duration: 5 * 1000 });

    //过期处理：给用户选 停留，登录
    if (status === 410000) {
      if (_choose) return Promise.reject(response);
      _choose = true;
      ElMessageBox.confirm(
        "您的登录已过期，您可以取消停留在此页面，或确认重新登录",
        "登录过期",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        }
      )
        .then(() => {
          //清除session，去登录页
          store.commit("setUser", null);
          router.push({
            name: "login",
            query: {
              redirect: router.currentRoute.value.fullPath,
            },
          });
        })
        .finally(() => {
          _choose = false;
        });
    }

    return Promise.reject(response);
  },
  (err) => {
    ElMessage({ type: "error", message: err.message, duration: 5 * 1000 });
    return Promise.reject(err);
  }
);

// export default request
export default <T = any>(config: AxiosRequestConfig) => {
  return request(config).then((res) => {
    return (res.data.data || res.data) as T;
  });
};
